// upgrade-contracts.js
// 执行合约升级的脚本，用于部署新的实现合约并将代理合约指向新的实现

const hre = require("hardhat");
const { ethers, upgrades } = require("hardhat");
const fs = require("fs");
const path = require("path");

async function main() {
  console.log("开始执行合约升级...");

  // 获取部署账户
  const [deployer] = await ethers.getSigners();
  console.log(`使用部署账户: ${deployer.address}`);
  
  // 加载之前的部署信息
  const networkName = hre.network.name;
  const deploymentPath = path.join("./deployments", `${networkName}-deployments.json`);
  
  if (!fs.existsSync(deploymentPath)) {
    console.error(`未找到部署信息文件: ${deploymentPath}`);
    console.error("请先运行deploy-upgradeable.js脚本部署可升级合约");
    process.exit(1);
  }
  
  const deploymentInfo = JSON.parse(fs.readFileSync(deploymentPath, "utf8"));
  console.log("已加载部署信息:", deploymentInfo);
  
  // 升级AuctionFactory合约
  console.log("\n升级AuctionFactory合约...");
  const AuctionFactoryV2 = await ethers.getContractFactory("AuctionFactory"); // 注意：这应该是更新后的合约代码
  
  console.log(`准备升级代理合约，地址: ${deploymentInfo.auctionFactoryProxy}`);
  const upgradedAuctionFactory = await upgrades.upgradeProxy(
    deploymentInfo.auctionFactoryProxy,
    AuctionFactoryV2,
    { kind: "uups" }
  );
  
  await upgradedAuctionFactory.waitForDeployment();
  console.log(`AuctionFactory代理升级完成，地址: ${await upgradedAuctionFactory.getAddress()}`);
  
  const newImplementation = await upgrades.erc1967.getImplementationAddress(
    await upgradedAuctionFactory.getAddress()
  );
  console.log(`AuctionFactory新的实现合约地址: ${newImplementation}`);
  
  // 升级CrossChainAuctionManager合约
  console.log("\n升级CrossChainAuctionManager合约...");
  const CrossChainAuctionManagerV2 = await ethers.getContractFactory("CrossChainAuctionManager"); // 注意：这应该是更新后的合约代码
  
  console.log(`准备升级代理合约，地址: ${deploymentInfo.crossChainManagerProxy}`);
  const upgradedCrossChainManager = await upgrades.upgradeProxy(
    deploymentInfo.crossChainManagerProxy,
    CrossChainAuctionManagerV2,
    { kind: "uups" }
  );
  
  await upgradedCrossChainManager.waitForDeployment();
  console.log(`CrossChainAuctionManager代理升级完成，地址: ${await upgradedCrossChainManager.getAddress()}`);
  
  const newCrossChainImplementation = await upgrades.erc1967.getImplementationAddress(
    await upgradedCrossChainManager.getAddress()
  );
  console.log(`CrossChainAuctionManager新的实现合约地址: ${newCrossChainImplementation}`);

  // 更新部署信息文件
  const updatedInfo = {
    ...deploymentInfo,
    updatedAt: new Date().toISOString(),
    previousAuctionFactoryImpl: deploymentInfo.auctionFactoryImpl,
    auctionFactoryImpl: newImplementation,
    previousCrossChainManagerImpl: deploymentInfo.crossChainManagerImpl,
    crossChainManagerImpl: newCrossChainImplementation,
  };
  
  fs.writeFileSync(
    deploymentPath,
    JSON.stringify(updatedInfo, null, 2)
  );
  
  console.log(`\n升级信息已更新至: ${deploymentPath}`);
  console.log("\n合约升级完成！");
  
  // 可选：验证新的实现合约
  if (["sepolia", "goerli", "mainnet"].includes(networkName)) {
    console.log("\n准备验证新的实现合约...");
    try {
      console.log(`验证AuctionFactory实现合约: ${newImplementation}`);
      await hre.run("verify:verify", {
        address: newImplementation
      });
      
      console.log(`验证CrossChainAuctionManager实现合约: ${newCrossChainImplementation}`);
      await hre.run("verify:verify", {
        address: newCrossChainImplementation
      });
      
      console.log("合约验证完成！");
    } catch (error) {
      console.error("合约验证失败:", error);
    }
  }
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  }); 